package com.yhb.service.impl;

import com.yhb.channel.provider.event.IPayChannelEventBus;
import com.yhb.model.MQMessage;
import com.yhb.model.mq.ChannelEvent;
import com.yhb.service.MQService;
import lombok.extern.log4j.Log4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Log4j
public class ChannelEventBusImpl implements IPayChannelEventBus {
    private final List<Handler> handlers = new ArrayList<>();

    @Qualifier("MQServiceImpl")
    @Autowired
    @Lazy
    private MQService mqService;

    @Override
    public void emit(String payload) {
        mqService.sendMsg(MQMessage.builder()
                .type(MQMessage.T_CHANNEL_EVENT_BUS)
                .content(ChannelEvent.builder()
                        .payload(payload)
                        .build())
                .build());
    }

    @Override
    public void on(Handler handler) {
        handlers.add(handler);
    }

    public void onEvent(String payload) {
        for (var h : handlers) {
            try {
                h.on(payload);
            } catch (Throwable t) {
                log.error("consume event err:", t);
            }
        }
    }
}
